package sys

import (
	"ginweb-admin/global"
	"ginweb-admin/model/entity/sys"
)

type SysUserRoleService struct{}

// 用户授权角色
func (service *SysUserRoleService) SaveSysUserRole(userId uint, sysUserRole []*sys.SysUserRole) (err error) {

	// 开启事务
	db := global.DB.Begin()
	// 删除用户对应的角色
	if err := db.Where("user_id = ?", userId).Delete(&sys.SysUserRole{}).Error; err != nil {
		// 事务回滚
		db.Rollback()
		return err
	}
	// 保存用户和角色的关系
	if err := db.Create(sysUserRole).Error; err != nil {
		// 事务回滚
		db.Rollback()
		return err
	}

	// 提交事务
	return db.Commit().Error
}

// 查询用户授权的角色
func (service *SysUserRoleService) FindUserRole(userId uint) (sysRole []*sys.SysRole, err error) {
	err = global.DB.Select("t2.* ").Table("sys_user_role t1,sys_role t2").
		Where("t1.role_id = t2.id and t2.is_deleted = 0 and t1.user_id = ?", userId).
		Scan(&sysRole).Error
	return sysRole, err
}
